//
//  RMMUpOrderViewController.m
//  Romomo
//
//  Created by puman on 16/10/11.
//  Copyright © 2016年 mazegong. All rights reserved.
//

#import "RMMUpOrderViewController.h"
#import "RMMUpOrderDateTableViewCell.h"
#import "RMMUpOrederGoodsTableViewCell.h"
#import "RMMConfirmOrderView.h"
#import "RMMUpOrderYouHuiDetailTableViewCell.h"
#import "RMMOderAdressViewController.h"
#import "RMMChosseDateViewController.h"
#import "RMMAdressTableViewCell.h"
#import "RMMPayOrderViewController.h"
#import "RMMChooseSkillViewController.h"

@interface RMMUpOrderViewController ()<UITableViewDelegate, UITableViewDataSource>

@end

@implementation RMMUpOrderViewController
{
    UITableView *_tableView;
    UILabel *_countLabel; // 件数
    RMMConfirmOrderView *_confirmOrderView;
    NSNumber *_number;
    NSDictionary *_adressDic;
    NSString *_adress_id;
    NSString *_chooseTime;
    NSString *_skillNumber;
    CGFloat _yanzhiMoney;
    CGFloat _totalPrice;
}
- (void)dealloc{
    if (![[RMMFileManager shareHandle].fromSkillType isEqualToString:@"1"]) {
        [[RMMFileManager shareHandle].bookingDic removeAllObjects];
    }
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([[RMMFileManager shareHandle].bookingDic allKeys].count) {
        [_tableView reloadData];
        if ([[RMMFileManager shareHandle].bookingDic allKeys].count == 3) {
            _confirmOrderView.confirmOderBut.backgroundColor = kBasicColor;
            _confirmOrderView.confirmOderBut.userInteractionEnabled = YES;
            [_confirmOrderView.confirmOderBut setTitleColor:kWhiteColor forState:(UIControlStateNormal)];
        } else {
            _confirmOrderView.confirmOderBut.backgroundColor = RGBA(238, 238, 238, 1);
            _confirmOrderView.confirmOderBut.userInteractionEnabled = NO;
            [_confirmOrderView.confirmOderBut setTitleColor:RGBA(224, 224, 224, 1) forState:(UIControlStateNormal)];
        }
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kWhiteColor;
    self.navigationItem.title = @"提交订单";
    _number = @0;
    [self addViews];
    // Do any additional setup after loading the view.
}
- (void)addViews{
    _yanzhiMoney = 0.00;
    _totalPrice = 0.00;
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64 - 49) style:(UITableViewStylePlain)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    [_tableView registerClass:[RMMUpOrederGoodsTableViewCell class] forCellReuseIdentifier:@"GoodsCell"];
    [_tableView registerClass:[RMMUpOrderDateTableViewCell class] forCellReuseIdentifier:@"DateCell"];
    [_tableView registerClass:[RMMUpOrderYouHuiDetailTableViewCell class] forCellReuseIdentifier:@"YouHuiCell"];
    [_tableView registerClass:[RMMAdressTableViewCell class] forCellReuseIdentifier:@"AdressCell"];

    [self.view addSubview:_tableView];
    [self addBottomView];
}
- (void)addBottomView{
    _confirmOrderView = [[RMMConfirmOrderView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 49 - 64, kScreenWideth, 49)];
    CGFloat totalPrice = [self getToatalPriceWithArray:_dataArray];
    _totalPrice = totalPrice;
    NSString *is_face = [_youHuiDic objectForKey:@"是否使用颜值"];
    if ([is_face isEqualToString:@"1"]) {
        _yanzhiMoney = [[_youHuiDic objectForKey:@"颜值"] floatValue];
        NSString *is_youHui = [_youHuiDic objectForKey:@"是否使用优惠券"];
        if ([is_youHui isEqualToString:@"1"]) {
            NSDictionary *dic = [_youHuiDic objectForKey:@"优惠券信息"];
            NSString *type = [NSString stringWithFormat:@"%@",dic[@"CARD_TYPE"]];
            if ([type isEqualToString:@"4"]) {
                // 折扣
                NSString *zekou = dic[@"DISCOUNT_RATE"];
                _totalPrice = totalPrice * [zekou floatValue] - _yanzhiMoney;
            } else if ([type isEqualToString:@"6"]) {
                // 带金券
                NSString *daiMoney = dic[@"PAR_AMT"];
                _totalPrice = totalPrice - [daiMoney floatValue] - _yanzhiMoney;
            }
        } else {
            _totalPrice = totalPrice - _yanzhiMoney;
        }

    } else {
        NSString *is_youHui = [_youHuiDic objectForKey:@"是否使用优惠券"];
        if ([is_youHui isEqualToString:@"1"]) {
            NSDictionary *dic = [_youHuiDic objectForKey:@"优惠券信息"];
            NSString *type = [NSString stringWithFormat:@"%@",dic[@"CARD_TYPE"]];
            if ([type isEqualToString:@"4"]) {
                // 折扣
                NSString *zekou = dic[@"DISCOUNT_RATE"];
                _totalPrice = totalPrice * [zekou floatValue] - _yanzhiMoney;
            } else if ([type isEqualToString:@"6"]) {
                // 带金券
                NSString *daiMoney = dic[@"PAR_AMT"];
                _totalPrice = totalPrice - [daiMoney floatValue] - _yanzhiMoney;
            }
        } else {
            _totalPrice = totalPrice - _yanzhiMoney;
        }
    }
    _confirmOrderView.totalPrice.text = [NSString stringWithFormat:@"¥%.2f",_totalPrice];
    [_confirmOrderView.confirmOderBut setTitle:@"提交" forState:(UIControlStateNormal)];
    _confirmOrderView.confirmOderBut.backgroundColor = RGBA(238, 238, 238, 1);
    [_confirmOrderView.confirmOderBut setTitleColor:RGBA(224, 224, 224, 1) forState:(UIControlStateNormal)];
    _confirmOrderView.confirmOderBut.userInteractionEnabled = NO;
    BUTTON_S(_confirmOrderView.confirmOderBut, confirmOderBut);
    _confirmOrderView.confirmOderBut.hidden = NO;
    [self.view addSubview:_confirmOrderView];
    if ([[RMMFileManager shareHandle].fromSkillType isEqualToString:@"1"]) {
        _confirmOrderView.confirmOderBut.backgroundColor = kBasicColor;
        _confirmOrderView.confirmOderBut.userInteractionEnabled = YES;
        [_confirmOrderView.confirmOderBut setTitleColor:kWhiteColor forState:(UIControlStateNormal)];
    }
}
// 提交
- (void)confirmOderBut{
    BOOL isT = NO;
    for (RMMShopingModel *model in _dataArray) {
        if ([model.MY_CARD_ID isEqualToString:@"0"]) {
            isT = YES;
            break;
        }
    }
    if (isT) {
        RMMPayOrderViewController *VC = [[RMMPayOrderViewController alloc] init];
        VC.dataDic = _dataDic;
        VC.dataArray = _dataArray;
        VC.youHuiDic = _youHuiDic;
        VC.isHome = _isHome;
        VC.totalPrice = [NSString stringWithFormat:@"%.2f",_totalPrice];
        [self.navigationController pushViewController:VC animated:YES];

    } else {
         NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
         NSString *cust_id = [RMMFileManager retrunObjWith:[RMMFileManager shareHandle].userDic[@"CUST_ID"]];
         parDic[@"org_no"] = Org_no;
         parDic[@"cust_id"] = cust_id;
         parDic[@"order_id"] = _dataDic[@"OrderId"];
         parDic[@"payment"] = @"0.00";
         parDic[@"pay_way_code"] = @"999";
         parDic[@"is_home"] = _isHome;
         parDic[@"region_id"] = [RMMFileManager shareHandle].region_id;
         NSDictionary *skillDic = [[RMMFileManager shareHandle].bookingDic objectForKey:@"技师"];
         parDic[@"masseur"] = skillDic[@"EMP_ID"];
        NSDictionary *dic = [[RMMFileManager shareHandle].bookingDic objectForKey:@"地址"];
        id adress_id = [dic objectForKey:@"ID"];

        if ([_isHome isEqualToString:@"1"]) {
            parDic[@"store_id"] = @"-10";
            parDic[@"adder_id"] = adress_id;
        } else {
            parDic[@"store_id"] = adress_id;
            parDic[@"adder_id"] = @"-1";
        }
         parDic[@"begin_time"] = [[RMMFileManager shareHandle].bookingDic objectForKey:@"时间"];
         parDic[@"long_time"] = [RMMFileManager shareHandle].totalTimeLength;
         NSMutableArray *array = [NSMutableArray array];
         for (RMMShopingModel *model in _dataArray) {
         NSMutableDictionary *dic = [NSMutableDictionary dictionary];
             dic[@"my_card_id"] = model.MY_CARD_ID;
             dic[@"ser_id"] = model.SERVICE_ID;
             dic[@"ser_name"] = model.SERVICE_NAME;
             dic[@"prod_cnt"] = [NSString stringWithFormat:@"%@",model.COUNT];
             dic[@"price"] = model.PRICE;
             [array addObject:dic];
         }
         parDic[@"serlist"] = array;
         parDic[@"who"] = @"0";
         NSString *url = BuyFuWuUrl;
         [OSRequestManager requestWithUrlString:url parDic:parDic method:POST finish:^(NSDictionary *dataDic) {
         NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
         if ([status isEqualToString:@"1"]) {
             [RMMFileManager shareHandle].thred = @"1";
             NS_POST(@"SHOPFRESH", nil, nil);
             NS_POST(@"ORDERUPDATA", nil, nil);
             [MMProgressHUD show];
             [MMProgressHUD dismissWithSuccess:@"预约成功!" title:nil afterDelay:1.0];
             [RMMFileManager shareHandle].fromSkillType = @"0";
             [[RMMFileManager shareHandle].bookingDic removeAllObjects];
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 [self.navigationController popToRootViewControllerAnimated:YES];
             });
             [[RMMFileManager shareHandle].bookingDic removeAllObjects];
             } else {
                 
             [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
             }
             } error:^(NSError *errors) {
             
            } view:self.view];
    }

}
- (void)payOrderWith:(NSString *)string{
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 2;
    } else if (section == 3) {
        return 1;
    } else if (section == 4) {
        return 1;
    }
    return _dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 78;
    } else if (indexPath.section == 1 || indexPath.section == 4) {
        return 49;
    } else if (indexPath.section == 2) {
        return 54;
    } else {
        return 70;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 16)];
        view.backgroundColor = RGBA(245, 246, 247, 1);
        return view;
    } else if (section == 2) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 44)];
        view.backgroundColor = kWhiteColor;
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 2 * kHalf, view.height)];
        label.text = @"订单汇总";
        label.textColor = COLORFROMCODE(0x4A4A4A, 1);
        label.font = kFont(13);
        [view addSubview:label];
        
        _countLabel = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWideth - 115, 0, 100, view.height)];
        _countLabel.textAlignment = NSTextAlignmentRight;
        _countLabel.text = [NSString stringWithFormat:@"%ld件",_dataArray.count];
        _countLabel.textColor = COLORFROMCODE(0x4A4A4A, 1);
        _countLabel.font = kFont(13);
        [view addSubview:_countLabel];
        return view;
    } else {
        return nil;
    }

}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 16;
    } else if (section == 2) {
        return 44;
    } else {
        return 0;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 16)];
    view.backgroundColor = RGBA(245, 246, 247, 1);
    if (section == 0 || section == 1 || section == 4) {
        return view;
    } else {
        return nil;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0 || section == 1 || section == 4) {
        return 16;
    } else {
        return 0; 
    }
 
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        RMMAdressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AdressCell"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.tag = 10;
        NSDictionary *dic = [RMMFileManager setValueForDic:[[RMMFileManager shareHandle].bookingDic objectForKey:@"地址"]];
        if ([dic allKeys].count) {
            cell.titleLabel.text = @"地址已选";
            cell.number = @2;
            cell.dic = dic;
        } else {
            cell.number = _number;
        }
        return cell;
    } else if (indexPath.section == 1) {
        RMMUpOrderDateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DateCell"];
        cell.tag = 11 + indexPath.row;
        if (indexPath.row == 0) {
            cell.titleLabel.text = @"日期/时间";
            NSString *time = [[RMMFileManager shareHandle].bookingDic objectForKey:@"时间"];
            if (time.length) {
                cell.contentLabel.text = time;
            } else {
                cell.contentLabel.text = @"选择时间";
            }

        } else {
            cell.titleLabel.text = @"服务技师";
            NSDictionary *skillDic = [[RMMFileManager shareHandle].bookingDic objectForKey:@"技师"];
            NSString *name = skillDic[@"EMP_NAME"];
            if (name.length) {
                cell.contentLabel.text = name;
            } else {
                cell.contentLabel.text = @"选择技师";
            }
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    } else if (indexPath.section == 2) {
        RMMUpOrederGoodsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GoodsCell"];
        cell.model = _dataArray[indexPath.row];
        return cell;
    } else if (indexPath.section == 4) {
        RMMUpOrderDateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DateCell"];
        cell.titleLabel.text = @"订单金额:";
        cell.titleLabel.font = kFont(14);
        cell.titleLabel.textColor = COLORFROMCODE(0x9B9B9B, 1);
        cell.contentLabel.text = [NSString stringWithFormat:@"¥%.2f",_totalPrice];
        cell.contentLabel.font = kFont(18);
        return cell;
    } else {
        RMMUpOrderYouHuiDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YouHuiCell"];
        cell.dic = _youHuiDic;
        return cell;
    }
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (![[RMMFileManager shareHandle].fromSkillType isEqualToString:@"1"]) {
        if (indexPath.section == 0) {
            RMMOderAdressViewController *VC = [[RMMOderAdressViewController alloc] init];
            if ([[RMMFileManager shareHandle].fromSkillType isEqualToString:@"1"]) {
                VC.type = @"1";
            }
            VC.isHome = _isHome;
            VC.goodsArray = _dataArray;
            [self.navigationController pushViewController:VC animated:YES];
        } else if (indexPath.section == 1) {
            if (![RMMFileManager shareHandle].isAddBookingOrder) {
                RMMAdressTableViewCell *cell = [self.view viewWithTag:10];
                if ([cell.titleLabel.text isEqualToString:@"请选择服务地址"]) {
                    cell.warning = @"OK";
                    _number = @5;
                    [_tableView reloadData];
                    return;
                }
                if (indexPath.row == 0) {
                    if ([[RMMFileManager shareHandle].bookingDic allKeys].count >= 2) {
                        [[RMMFileManager shareHandle].bookingDic removeObjectForKey:@"技师"];
                    }
                    RMMChosseDateViewController *VC = [[RMMChosseDateViewController alloc] init];
                    VC.isHome = _isHome;
                    [self.navigationController pushViewController:VC animated:YES];
                } else {
                    RMMChooseSkillViewController *VC = [[RMMChooseSkillViewController alloc] init];
                    VC.isHome = _isHome;
                    [self.navigationController pushViewController:VC animated:YES];
                }
            }
        }
    }
}
- (CGFloat)getToatalPriceWithArray:(NSArray *)array{
    CGFloat totalPrcie = 0.00;
    for (RMMShopingModel *model in array) {
        if ([model.isSelect isEqualToString:@"1"]) {
            if ([model.MY_CARD_ID isEqualToString:@"0"]) {
                CGFloat prcie = [model.PRICE floatValue];
                NSInteger count = [model.COUNT integerValue];
                totalPrcie += prcie * count;
            }
        }
    }
    return totalPrcie;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
